<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Doozer: DQML Builder</title>
    <style type="text/css" media="screen">
      body {
        margin: 0;
        margin-bottom: 25px;
        padding: 0;
        background-color: #f0f0f0;
        font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
        font-size: 13px;
        color: #333;
      }
      
      h1 {
        font-size: 28px;
        color: #000;
      }
      
	  h3 {
        font-size: 20px;
        color: #000;
      }

      a  {color: #03c}
      a:hover {
        background-color: #03c;
        color: white;
        text-decoration: none;
      }

	  #info {
		color: #FF00FF;
      }
      
      
      #page {
        background-color: #f0f0f0;
        width: 750px;
        margin: 0;
        margin-left: auto;
        margin-right: auto;
      }
      
      #content {
        float: left;
        background-color: white;
        border: 3px solid #aaa;
        border-top: none;
        padding: 25px;
        width: 750px;		
      }

      #footer {
        clear: both;
      }
      

      #header, #about, #builder-ui {
        padding-left: 75px;
        padding-right: 30px;
      }

      #header {
        
        background-repeat: no-repeat;
        background-position: top left;
        height: 64px;
      }
      #header h1, #header h2 {margin: 0}
      #header h2 {
        color: #888;
        font-weight: normal;
        font-size: 16px;
      }                
      
      #rets-info {
        border-top: 1px solid #ccc;
        margin-top: 25px;
        padding-top: 15px;
      }
      #rets-info h1 {
        margin: 0;
        font-size: 20px;
      }    

      td.label {
		float: right;		
	  }
	  td.label:after {content: ":"}		  	  
	  tr.required td.label {
		font-weight: bold;
	 }
	  td.searchable {
		font-weight: bold;
	}
	 span#metdata td.label {
		font-weight: bold;
	}
    </style>
    <script type="text/javascript" src="javascripts/prototype.js"></script>
    <script type="text/javascript" src="javascripts/effects.js"></script>
    <script type="text/javascript" >
	var blind_dur = 0.25;
	var sf_cols = 4;

	function login() {

	    var server_info = build_rets_info();

	    //Post the data to the doozer server.			
	    if (server_info != null) {
	        new Effect.BlindUp('metadata', {
	            duration: blind_dur
	        })
	        prepare_for_login();
	        $('login-loading').show();
	        new Ajax.Request('rets/login', {
	            postBody: Object.toJSON(server_info),
	            contentType: 'application/json',
	            requestHeaders: {
	                Accept: 'application/json'
	            },
	            onSuccess: function(transport) {
	                var metadata = transport.responseText.evalJSON();
	                $('login-loading').hide();
	                display_system_info(metadata["server_info"]);
	                populate_resources(metadata["resources"]);
	                new Effect.BlindDown('metadata', {
	                    duration: blind_dur
	                });
	            },
	            on500: function(transport) {
	                error = transport.responseText.evalJSON();
	                $('login-loading').hide();
	                alert(error.message)
	            },
	            onFailure: function(transport) {
	                alert('Error!');
	            }
	        });
	    }
	    return false;
	}

	function prepare_for_login() {
	    prepare_fields();

	    var resource = $('resource');
	    var rClass = $('class');

	    //Empty the selects			
	    resource.length = 0;
	    rClass.length = 0;

	    //Put in the first options
	    var first_resource = new Option("Select Resource", "");
	    first_resource.id = 'select_resource';
	    resource.add(first_resource, null);

	    //Reset the class dropdown
	    rClass.add(new Option("Select Class First", ""), null);
	    rClass["disabled"] = true;


	}

	function prepare_fields() {
	    //Remove All Inner HTML from select fields
	    $('query').hide();
	    $('search-section').innerHTML = "";
	    $('retrieved_fields').innerHTML = "";

	}

	function build_rets_info() {
	    var rets_info = {};
	    var fields = $$('tr.rets-info');
	    for (var i = 0; i < fields.length; i++) {
	        var row = fields[i];
	        var field = row.select('.field')[0];
	        if (field.value != null && !field.value.blank()) {
	            rets_info[field.id] = field.value;
	        } else {
	            if (row.hasClassName('required')) {
	                alert("Field '" + row.select('.label')[0].innerHTML + "' is required.");
	                return null;
	            }
	        }
	    }

	    //Test that the url is valid
	    if (!isURL(rets_info["url"])) {
	        alert("Login URL not valid");
	        return null;
	    }

	    return {
	        "rets_info": rets_info
	    };
	}

	function build_resource_and_class_info() {
	    var server_info = build_rets_info();
	    server_info["resource"] = $('resource').value;
	    server_info["class"] = $('class').value;
	    return server_info;
	}

	function display_system_info(system_info) {
	    $('system_id').innerHTML = system_info.system_id;
	    $('description').innerHTML = system_info.description;
	    $('comment').innerHTML = system_info.comment;
	}

	function populate_resources(resources) {
	    select = $('resource')
	    for (var i = 0, len = resources.length; i < len; i++) {
	        var resource = resources[i];
	        option = new Option(paren(resource.visible_name, resource.standard_name), resource.system_name);
	        option["rets_classes"] = resource.classes;
	        select.add(option, null);
	    }
	}

	function resource_selected() {

	    var res_select = $('resource');
	    var first_option = $('select_resource');
	    if (first_option) {
	        res_select.remove(first_option);
	    }

	    //Get the class select and change it.
	    var cl_select = $('class');
	    cl_select.options.length = 0;
	    var select_class_option = new Option("Select Class...", "")
	    select_class_option.id = "select_class";
	    cl_select.options.add(select_class_option, null);
	    cl_select.disabled = false;

	    var resource = res_select.options[res_select.selectedIndex];
	    for (var i = 0, len = resource.rets_classes.length; i < len; i++) {
	        var rClass = resource.rets_classes[i];
	        cl_select.add(new Option(paren(rClass.visible_name, rClass.standard_name), rClass.system_name), null)
	    }
	}

	function class_selected() {
	    var rClass = $('class');
	    var first_option = $('select_class');
	    if (first_option) {
	        rClass.remove(first_option);
	    }

	    var server_info = build_resource_and_class_info();

	    var loading_fields = $('loading_fields');
	    loading_fields.show();

	    new Ajax.Request('rets/fields', {
	        postBody: Object.toJSON(server_info),
	        contentType: 'application/json',
	        requestHeaders: {
	            Accept: 'application/json'
	        },
	        onSuccess: function(transport) {
	            var metadata = transport.responseText.evalJSON();
	            prepare_query_section(metadata);
	            loading_fields.hide();
	            new Effect.BlindDown('query', {
	                duration: blind_dur
	            });
	        },
	        on500: function(transport) {
	            loading_fields.hide();
	            error = transport.responseText.evalJSON();
	            alert(error.message)
	        },
	        onFailure: function(transport) {
	            alert('Error!');
	        }
	    });

	}

	function prepare_query_section(fields) {
	    var metadata = [];
	    var search_section = $('search-section');
	    search_section['metadata'] = metadata;
	    search_section['groups'] = [];
	    fields.each(function(field) {
	        field['display_name'] = paren(field['long_name'], field['standard_name']);
	        if (field['searchable']) {
	            metadata.push(field);
	        }
	    });

	    //Prepare the retrieved fields.
	    var retrieved_fields = $('retrieved_fields');
	    for (var i = 0, len = fields.length, row = null; i < len; i++) {
	        var field = fields[i];
	        if (i % sf_cols == 0) {
	            row = document.createElement("tr");
	            retrieved_fields.appendChild(row);
	        }
	        var checkbox_cell = document.createElement("td");
	        var checkbox = document.createElement("input");
	        checkbox.id = field.system_name + "-cbx";
	        checkbox.type = "checkbox";
	        checkbox['search_count'] = 0;
	        checkbox.onclick = toggle_retrieved_class_function(checkbox);
	        checkbox["metadata"] = field;
	        checkbox_cell.appendChild(checkbox);
	        row.appendChild(checkbox_cell);
	        fieldname_cell = document.createElement("td");
	        field["display_name"] = paren(field.long_name, field.standard_name);

	        fieldname_cell.innerHTML = field["display_name"];
	        row.appendChild(fieldname_cell);
	    }
	}

	function toggle_retrieved_class_function(checkbox) {
	    return function() {
	        checkbox.checked ? checkbox.addClassName("selected-field") : checkbox.removeClassName("selected-field")
	    }
	}
	
	function add_group() {
		//Create the new row and set it up
		var search_section = $('search-section');
		var group_row = $('group-template').clone(true);
		group_row.id = "";						
		search_section.appendChild(group_row);						
		edit_group(group_row);
		
		//Make the add button create a term for this group
		group_row.select('.add-button')[0].onclick = function() {
			add_term(group_row);
		}		
		//Set the data
		group_row['group_data'] = {};
		group_row['group_data']['terms'] = [];
		
		//Show it	
		new Effect.SlideDown(group_row, {duration: blind_dur});						
	}
	
	function edit_group(group_row) {
		//Change the header
		var header = group_row.select('.group-header')[0];
		header.innerHTML = "";
		header.appendChild($('group-edit-template').clone(true));		
		
		//Set the save and cancel button actions
		(group_row.select(".group-save")[0]).onclick = function() {
			save_group(group_row);
		};				
		(group_row.select(".group-cancel")[0]).onclick = group_row['group_data'] ? 
					function(){cancel_group(group_row)} : function(){remove_group(group_row)};
		
		//Set the selected operator if needed
		if(group_row['group_data']) {
			$A(group_row.select(".group-operator")[0].options).each(function(option) {
	            option.selected = option.value == group_row['group_data']['operator'];
	        });
	
			//Blind up the sections that need to be disabled for editing
			group_row.select('.disable-for-edit').each(function(section) {
				Effect.BlindUp(section, {duration: blind_dur})});
		}		
	}
	
	function save_group(group_row) {
		//Get the operator
		var operator_select = group_row.select('.group-operator')[0];
						
		//Set the group data
		var search_section = $('search-section');
		group_row['group_data']['operator'] = get_selected_option_values(operator_select)[0];
		group_row['group_data']['operator_display'] = get_selected_option_display(operator_select)[0];
		
		//Push the group onto the list if needed		
		if(search_section['groups'].indexOf(group_row['group_data']) == -1) {
			search_section['groups'].push(group_row['group_data']);
		}
		
		cancel_group(group_row);
	}
	
	function cancel_group(group_row) {
		//Change the table data elements
		//Change the header
		var header = group_row.select('.group-header')[0];
		header.innerHTML = "";
		header.appendChild($('saved-group-template').clone(true));
		
		//Set the title
		set_group_title(group_row);
		
		//Set the operators on the buttons
		(group_row.select(".group-edit")[0]).onclick = function() {
			edit_group(group_row);
		};
		(group_row.select(".group-delete")[0]).onclick = function() {
			remove_group(group_row);
		};
		
		//Blind down the sections that were disabled for editing
		group_row.select('.disable-for-edit').each(function(section) {
			Effect.BlindDown(section, {duration: blind_dur})});
	}
	
	function set_group_title(group_row) {
		var group_data = group_row['group_data'];
		group_data['number'] = $('search-section')['groups'].indexOf(group_data) + 1;
		group_data['name'] = "Group " + group_data['number'];		
		
		//TODO: Change title of the terms that reference this group
		
		group_row.select('.group-title')[0].innerHTML = group_data['name'] + " (" + group_row['group_data']['operator_display'] + ")";
	}
	
	function remove_group(group_row) {		
		Effect.SlideUp(group_row, {duration: blind_dur, afterFinish: function(){
			
			//TODO: Remove terms that reference this group
			
			
			var search_section = $('search-section');
			search_section['groups'] = search_section['groups'].without(group_row['group_data']);
			group_row.remove();

			//Go through the remaining rows and reset the titles.
			$('search-section').childElements().each(function(group_row){
				set_group_title(group_row);
			});
		}});		
	}

	function add_term(group_row) {
	    var search_section = $('search-section');

	    //Creat the row
	    var row = $('term-template').clone(true);
	    row.hide();
	    row.id = "";
	    row['group_row'] = group_row;
	    edit_term(row);
	    row['term_data'] = {};		
	    
	    (group_row.select('.group-terms')[0]).appendChild(row);
	    new Effect.BlindDown(row, {
	        duration: blind_dur
	    });
	}

	function edit_term(row) {
	    //Set the field
	    var field = row.select(".field")[0];
	    field.innerHTML = "";
	    var select = $('term-field-template').clone(true);
	    select.id = "";
	
		//Set the onchange event
		select.onchange = function() {
			var option = select.options[select.selectedIndex];
			selected_term_field(row, option['metadata']);
			
		}
	    var groups_group = select.select(".groups-group")[0];
	    var fields_group = select.select(".fields-group")[0];

		//Add Groups to the field options
	    var groups = $('search-section')['groups'].without(row['group_row']['group_data']);		
	    if (groups.length > 0) {
	    	groups.each(function(group) {
	    		var option = new Option(group["name"], group["number"]);
	    		option['metadata'] = group;
	    		groups_group.appendChild(option);
	    	});
	    } else {
	    	groups_group.remove();
	    }

		//Add the Fields
	    $('search-section')['metadata'].each(function(metadata) {
	        var option = new Option(metadata["display_name"], metadata.system_name);
	        option['metadata'] = metadata;
	        fields_group.appendChild(option);
	    });
	    field.appendChild(select);

	    //Get the term data if there is any
	    var term_data = row["term_data"];

	    //Set the action buttons
	    var actions = row.select(".actions")[0];
	    actions.innerHTML = "";

	    //Save button
	    var save_button = $("save-button-template").clone(true);
	    save_button.id = "";
	    save_button.onclick = function() {
	        save_term(row);
	    }
	    actions.appendChild(save_button);

	    //Cancel Button
	    var cancel_button = $('cancel-button-template').clone(true)
	    cancel_button.id = "";
	    cancel_button.onclick = function() {
	        if (term_data) {
	            cancel_term(row);
	        } else {
	            remove_term(row);
	        }

	    }
	    actions.appendChild(cancel_button);

	    //If there is term_data, then set the existing values
	    if (term_data) {
	        //Get the metadata for the existing term
	        var metadata = term_data['metadata'];

	        //Set the selected option and call selected_term_field
	        $A(select.options).each(function(option) {
	            option.selected = option.value == term_data['field'];
	        });
	        selected_term_field(row, metadata);

	        //Set the selected operator
	        $A(row.select(".operator")[0].firstDescendant().options).each(function(option) {
	            option.selected = option.value == term_data['operator'];
	        });
	        selected_operator(row, metadata);

	        //Set the value
	        if (metadata['lookups']) {
	            var value
	            $A(row.select(".value")[0].firstDescendant().options).each(function(option) {
	                option.selected = term_data['value'].indexOf(option.value) > -1;
	            });
	        } else {
	            var values = term_data['value'];
	            var vfields = row.select('.value-data');
	            for (var i = 0, length = values.length; i < length; i++) {
	                vfields[i].value = values[i];
	            }
	        }
	    }

	    //Enable the save button if needed.
	    save_button.disabled = (term_data == null);

	}

	function selected_term_field(row, metadata) {

	    //Disable save
	    row.select('.save-button')[0].disabled = true;

	    //Set the metadata for the row
	    row['term_data']['metadata'] = metadata;

	    //Get the cells we need
	    var field = row.select(".field")[0];
	    var operator = row.select(".operator")[0];
	    var value = row.select(".value")[0];

	    //Remove the first option if is the Select Field one.
	    var select = field.firstDescendant();
	    var first_option = select.options[0];
	    if (first_option.value.blank()) {
	        select.remove(first_option);
	    }

	    //Clear the operator and value cells.
	    operator.innerHTML = "";
	    value.innerHTML = "";

	    //Set the operator fields based on the type of term (field, lookup or other term)
	    var operator_template = null;
	    if (metadata['lookups']) {
	        operator_template = 'lookup-operator-template';
	        row['term_data']['type'] = 'lookup';
	    } else if (metadata['terms']) {
	        operator_template = 'group-operator-template';
	        row.select('.save-button')[0].disabled = false;
	        row['term_data']['type'] = 'group';
	    } else {
	        operator_template = 'base-operator-template';
	        row['term_data']['type'] = 'base';
	    }
	    var operator_select = $(operator_template).clone(true);
	    operator_select.id = "";
		operator_select.onchange = function() {
			var option = operator_select.options[operator_select.selectedIndex];
			selected_operator(row, option['metadata']);
		}
	    $A(operator_select.options).each(function(option) {
			option['metadata'] = metadata;
	    });
	    operator.appendChild(operator_select);
	}

	function selected_operator(row, metadata) {
	    //Disable save
	    row.select('.save-button')[0].disabled = true;


	    //Get the cells we need
	    var operator = row.select(".operator")[0];
	    var value = row.select(".value")[0];

	    //Remove the first option if is the Select Operator is one
	    var select = operator.firstDescendant();
	    var first_option = select.options[0];
	    if (first_option.value.blank()) {
	        select.remove(first_option);
	    }

	    //Clear the value cell.
	    value.innerHTML = "";

	    //Set the value fields based on the type of term (field, lookup or other term)
	    var lookups = metadata['lookups'];
	    if (lookups) {
	        //Create a dropdown for the values based on the lookup values.
	        value_select = $('lookup-value-template').clone(true);
	        value_select.id = "";
	        lookups.each(function(lookup_value) {
	            var option = new Option(lookup_value['long'], lookup_value['value']);
	            option.onclick = function() {
	                selected_value(row, metadata);
	            }
	            value_select.add(option, null);
	        });
	        value.appendChild(value_select);

	    } else if (metadata['terms']) {
	        //Keep save active
	        row.select('.save-button')[0].disabled = false;
	    } else {
	        var operator = select.options[select.selectedIndex];
	        var length = operator.value.match(/\%/g).length;
	        for (var i = 0; i < length; i++) {
	            var textfield = $('base-value-template').clone(true);
	            textfield.id = "";
	            textfield.onkeyup = function() {
	                test_value_fields(row);
	            };
	            value.appendChild(textfield);
	        }
	    }
	}

	function test_value_fields(row) {
	    var save_button = row.select('.save-button')[0]
	    save_button.disabled = false;
	    $A(row.select('.value-data')).each(function(vfield) {
	        save_button.disabled = save_button.disabled || vfield.value.blank();
	    });
	}

	function selected_value(row, metadata) {
	    var value = row.select(".value")[0];

	    //Remove the first option if is the Select value is one
	    var select = value.firstDescendant();
	    var first_option = select.options[0];
	    if (first_option.value.blank()) {
	        select.remove(first_option);
	    }

	    //Enable the save button if there is an enabled options
	    var enabled = false;
	    $A(select.options).each(function(option) {
	        enabled = enabled || option.selected;
	    });

	    row.select('.save-button')[0].disabled = !enabled;
	}

	function save_term(row) {
	    var field = row.select(".field-data")[0];
	    var operator = row.select(".operator-data")[0];
	    var value = row.select('.value-data')[0];

	    var term_data = row['term_data'];

	    term_data['field'] = field.value;
	    term_data['field_display'] = get_selected_option_display(field);

	    term_data['operator'] = operator.value;
	    term_data['operator_display'] = get_selected_option_display(operator);

	    if (term_data['metadata']['lookups']) {
	        term_data['value'] = get_selected_option_values(value);
	        term_data['value_display'] = get_selected_option_display(value);
	    } else {
	        term_data['value'] = $A(row.select('.value-data')).collect(function(vfield) {
	            return vfield.value;
	        });
	        term_data['value_display'] = term_data['value'].join(" and ");
	    }

	    //Add and check any retrieved fields that are associted with this field
	    var checkbox = $(field.value + "-cbx");
	    if (checkbox) {
	        checkbox['search_count']++;
	        checkbox.checked = true;
	        checkbox.onclick();
	        checkbox.disabled = true;
	    }	   
	
		//Save the terms data now that this is done.
		row['group_row']['group_data']['terms'].push(row['term_data']);

	    cancel_term(row);
	}

	function cancel_term(row) {

	    var term_data = row['term_data'];

	    var field = row.select(".field")[0];
	    field.innerHTML = term_data['field_display'];

	    var operator = row.select(".operator")[0];
	    operator.innerHTML = term_data['operator_display'];

	    var value = row.select('.value')[0];
	    var escapedValue = "" + term_data['value_display'] + ""
	    value.innerHTML = escapedValue.escapeHTML();

	    var actions = row.select('.actions')[0];
	    actions.innerHTML = "";

	    //Edit button
	    var edit_button = $("edit-button-template").clone(true);
	    edit_button.id = "";
	    edit_button.onclick = function() {
	        edit_term(row);
	    }
	    actions.appendChild(edit_button);

	    //Remove Button
	    var remove_button = $('remove-button-template').clone(true)
	    remove_button.id = "";
	    remove_button.onclick = function() {
	        remove_term(row);
	    }
	    actions.appendChild(remove_button);	   
	}

	function remove_term(row) {

	    //Remove the terms from the group
	    var group_data = row['group_row']['group_data'];
	    group_data['terms'] = group_data['terms'].without(row['term_data']);	     
	    row.remove();	   
	}

	function get_selected_option_values(select) {
	    return get_selected_options_part(select,
	    function(option) {
	        return option.value;
	    });
	}

	function get_selected_option_display(select) {
	    return get_selected_options_part(select,
	    function(option) {
	        return option.innerHTML;
	    });
	}

	function get_selected_options_part(select, funct) {
	    var results = [];
	    $A(select.options).each(function(option) {
	        if (option.selected) {
	            results.push(funct(option));
	        }
	    });
	    return results;
	}

	function isURL(s) {
	    var regexp = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
	    return regexp.test(s);
	}

	function paren(name, paran_name) {
	    if (paran_name != null && !paran_name.blank() && name != paran_name) {
	        return name + " (" + paran_name + ")";
	    } else {
	        return name;
	    }
	}

	function submit_final(simple) {

	    //Build the DMQL stuff
	    var groups = $('search-section')['groups'].collect(function(group) {
	        return {
	            operator: group['operator'],
	            terms: group['terms'].collect(function(term) {
	                return {
	                    field: term['field'],
	                    operator: term['operator'],
	                    type: term['type'],
	                    value: term['value']
	                };
	            })
	        }
	    });
	    var query_info = {
	        groups: groups
	    };

	    //Prepare the AJAX call.
	    var location = "rets/";
	    var mime_type = "";
	    if (simple) {
	        location = location + "simple";
	        mime_type = "text/yaml";

	        //Add the retrieved fields
	        query_info['select'] = new Array();
	        $$('.selected-field').each(function(checkbox) {
	            var metadata = checkbox['metadata'];
	            query_info['select'].push(metadata.system_name);
	        })

	        //Merge in rets info
	        query_info = $H(query_info).merge(build_resource_and_class_info());
	    } else {
	        location = location + "dmql";
	        mime_type = "text/plain";
	    }

	    new Ajax.Request(location, {
	        postBody: Object.toJSON(query_info),
	        contentType: 'application/json',
	        requestHeaders: {
	            Accept: 'text/yaml'
	        },
	        onSuccess: function(transport) {
	            $('results').innerHTML = transport.responseText.escapeHTML();
	            Effect.BlindDown('results-table', {
	                duration: blind_dur
	            });
	        },
	        on500: function(transport) {
	            error = transport.responseText.evalJSON();
	            alert(error.message)
	        },
	        onFailure: function(transport) {
	            alert('Error!');
	        }
	    });
	}

    </script>
  </head>
  <body>
    <div id="page">      
      <div id="content">
        <div id="header">
          <h1>Welcome to Doozer</h1>
          <h2>The RETS DMQL builder from CRT.</h2>
        </div>
        
        <div id="builder-ui">
	      <div id="server-info">
          	<h3>RETS Server Information</h3>
			<span class="info">(None of this information is stored on the doozer server.)</span>
			<br/><br/>
		  	<form id="server-info-form" onsubmit="login();">
          		<table>			
		    		<tr class="rets-info required">
						<td class="label">RETS Server Login URL</td>
						<td><input type="textfield" id="url" size="30" class="field"/></td>
					</tr>
					<tr class="rets-info required">
						<td class="label">Username</td>
						<td><input type="textfield" id="username" size="30" class="field"/></td>
					</tr>
					<tr class="rets-info required">
						<td class="label">Password</td>
						<td><input type="textfield" id="password" size="30" class="field"/></td>
					</tr>
					<tr class="rets-info required">
						<td class="label">RETS Version</td>						
						<td>
							<select id="rets_version" class="field" >
								<option value="1.5">1.5</option>
								<option value="1.7">1.7</option>
								<option value="1.7.2" selected>1.7.2</option>							
							</select>
						</td>
					</tr>
					<tr class="rets-info">
						<td class="label">User-Agent</td>
						<td><input type="textfield" id="user_agent" size="30" class="field"/></td>
					</tr>
					<tr class="rets-info">
						<td class="label">User-Agent Password</td>
						<td><input type="textfield" id="user_agent_password" size="30" class="field"/></td>
					</tr>
					<tr class="rets-info">
						<td class="label">Interealty Server</td>
						<td>
							<input type="checkbox" id="user_agent_auth_interealty_check" onclick="$('user_agent_auth_interealty').value=$('user_agent_auth_interealty_check').checked">
							<input type="hidden" id="user_agent_auth_interealty" class="field">
						</td>
					</tr>
					<tr>
						<td colspan="2"><input type="button" value="Login" onclick="login();"/></td>
				    </tr>					
		  		</table>
				</div>
				<br/>
				<br/>	
				<span id="login-loading" style="display:none">Loading Metadata...</span>
				<div id="metadata" style="display:none">
					<table>
						<thead>
							<tr>
								<th colspan="2" align="center">System Information</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td></td>
								<td width="279px"></td>
							</tr>
							<tr>
								<td class="label">System ID</td>
								<td id="system_id" class="field"></td>
							</tr>
							<tr>
								<td class="label">Description</td>
								<td id="description" class="field"></td>
							</tr>
							<tr>
								<td class="label">Comment</td>
								<td id="comment" class="field"></td>
							</tr>
						</tbody>
					</table>
					<br/>
					<br/>
					<table width="100%">					
						<tr>
							<td class="label">Resource</td>
							<td>
								<select id="resource" class="field" onchange="prepare_fields();resource_selected();">
									<option id="">Select Resource...</option>
								</select>
							</td>
							<td class="label">Class</td>
							<td>
								<select id="class" class="field" disabled="true" onchange="prepare_fields();class_selected();;">
									<option>Select Resource First</option>
								</select>
							</td>
						</tr>
					</table>
					<br/>
					<br/>
					<span id="loading_fields" style="display:none">Loading Metadata...</span>
					<div id="query" style="display:none">
					<table border="0" cellspacing="5" cellpadding="5">						
						<thead>
							<tr>
								<th colspan="100" align="center">Search Groups</th>
							</tr>																				
						</thead>
						<tbody id="search-section"></tbody>
						<tfoot>
							<tr>
								<td><input id="add-term" type="button" value="Add Group" onclick="add_group();"></td>
							</tr>
						</tfoot>
					</table>
					<br/>
					<br/>
					<table>						
						<thead>
							<tr>
								<th colspan="100" align="center">Retrievable Fields</th>
							</tr>
						</thead>
					<tbody id="retrieved_fields"></tbody>
					</table>
					<br/>
					<br/>
					<table>
						<tr>
							<td><input type="button" value="Create DMQL" onclick="submit_final(false)"></td>
							<td><input type="button" value="Create simpleRETS Config File" onclick="submit_final(true)"/></td>
						</tr>												
					</table>
					<br/>
					<br/>
					<table style="display:none" id="results-table">
						<tr>
							<th>Results</th>
						</tr>
						<tr>
							<td><pre id="results"></pre></td>
						</tr>							
					</table>
					</div>
				</div>
		  	</form>		    
		 </div>
        </div>
      </div>      
      <div id="footer">
	  
   </div>
   <div id="templates" style="display:none;">
   <table>
   <tr id="group-template" style="display:none;">
     <td>
	   <table>
		<thead class="group-header"></thead>
		<tbody class="group-terms disable-for-edit" style="display:none;"></tbody>
		<tfoot class="group-footer disable-for-edit" style="display:none;">
		  	<tr>
			    <td>&nbsp;&nbsp;<input id="add-term" type="button" value="Add Term" class="add-button"></td>
			 </tr>
		</tfoot>
	   </table>	
	 </td>
   </tr>
   <tr id="group-edit-template" >
     <th>Select Group Type:</th> 
     <th>
	   <select class="group-operator">		
	     <option value=",">AND</option>
		 <option value="|">OR</option>		
	   </select>
	 </th>
	<th>
	  <input type="button" value="Cancel" class="group-cancel"/>
	  <input type="button" value="Save" class="group-save"/>
	</th>
   </tr>
   <tr id="saved-group-template">
	<th class="group-title"></th>
	<th>
	  <input type="button" value="Edit" class="group-edit"/>
	  <input type="button" value="Delete" class="group-delete"/>
	</th>
   </tr>   
   <tr id="term-template" class="term">	    
     <td class="field"></td>
	 <td class="operator"></td>
	 <td class="value"></td>
	 <td class="actions"></td>
   </tr>
   </table>
   <form>
	<select id="term-field-template" class="field-data">
		<option value="">Select Field or Group...</option>
		<optgroup class="groups-group" label="Groups"></optgroup>
		<optgroup class="fields-group" label="Fields"></optgroup>
	</select>
	<select id="base-operator-template" class="operator-data">
		<option value="">Select Operator...</option>
		<option value="=%">Equals</option>
		<option value="=%-%">Between</option>
		<option value="=%+">Greater or Equal</option>
		<option value="=%-">Less or Equal</option>
	</select>
	<select id="lookup-operator-template" class="operator-data">
		<option value="">Select Operator...</option>
		<option value="=|%" class="opvalue">In</option>
		<option value="=~%" class="opvalue">Not In</option>
	</select>
	<select id="group-operator-template" class="operator-data">
		<option value="%" class="opvalue">None</option>
		<option value="~%" class="opvalue">Negate</option>
	</select>
	<span id="group-negate-template"><input type="checkbox" value="~%" class="operator-data"/> Negate</span>
	<select id="lookup-value-template" class="value-data" multiple="true" size=""></select>
	<input id="base-value-template"  type="text" value="" class="value-data" size="10"/>
	<input id="save-button-template" type="button" value="Save" disabled="true" class="save-button"/>
	<input id="edit-button-template" type="button" value="Edit" class="edit-button"/>
	<input id="cancel-button-template" type="button" value="Cancel" class="cancel-button"/>
	<input id="remove-button-template" type="button" value="Remove" class="delete-button"/>
	</form>
  </div>
 </body>
</html>